/**
 * edatagrid - jQuery EasyUI
 * 
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2011 stworthy [ stworthy@gmail.com ] 
 * 
 * Dependencies:
 *   datagrid
 *   messager
 * 
 */
(function($){
	function buildGrid(target) {
		var opts = $.data(target, 'edatagrid').options;
		//根据cookie中保存的列宽，修改opts
		//需要对treegrid也能保存用户的列宽的调整
		if(opts.url) {
			var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
			var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
			urlid = urlid.substring(0, myindex);
			urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
			var acookie = readCookie('_colwidth_' + urlid);
			//如果cookie中存在列宽的设置，则对列宽重新赋值
			if(acookie) {
				var values = JSON.parse(acookie);
				var opt = opts.columns[0];
				var frozenOpt = opts.frozenColumns[0];
				//非固定列保存列宽设置
				for(var i in values) {
					if(values[i].width != null) {
						for(var j in opt) {
							if(values[i].field === opt[j].field) {
								opt[j].width = values[i].width;
								break;
							}
						}
					}
				}
				//固定列保存列宽设置
				for(var i in values) {
					if(values[i].width != null) {
						for(var j in frozenOpt) {
							if(values[i].field == frozenOpt[j].field) {
								frozenOpt[j].width = values[i].width;
								break;
							}
						}
					}
				}
			}
		} else {
			//如果没有url说明是新增表，以baseURI与id拼接出唯一键，在cookie中记录列宽
			var baseUrl = (target.baseURI || document.URL);
			var urlid = baseUrl.substring(baseUrl.indexOf("entityName=")+11, baseUrl.length);
			var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
			urlid = urlid.substring(0, myindex);
			urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
			urlid = urlid + "_" + target.id;
			var acookie = readCookie('_colwidth_' + urlid);
			//如果cookie中存在列宽的设置，则对列宽重新赋值
			if(acookie) {
				var values = JSON.parse(acookie);
				var opt = opts.columns[0];
				var frozenOpt = opts.frozenColumns[0];
				for(var i in values) {
					if(values[i].width != null) {
						for(var j in opt) {
							if(values[i].field == opt[j].field) {
								opt[j].width = values[i].width;
								break;
							}
						}
					}
				}
				for(var i in values) {
					if(values[i].width != null) {
						for(var j in frozenOpt) {
							if(values[i].field == frozenOpt[j].field) {
								frozenOpt[j].width = values[i].width;
								break;
							}
						}
					}
				}
			}
		}
		var _isCheckFlag_ = true; //标示是否是勾选复选框选中行的，true - 是 , false - 否
		if(opts.tree) {
			$(target).treegrid($.extend({}, opts, {
				singleSelect:false,
				checkOnSelect:!opts.editing,
				ctrlSelect:true,
				onClickCell:function(field,data){
					if (opts.editing || (opts.editRowMap && opts.editRowMap[data.autoCode])){
						$(this).edatagrid('editCol',{"index":data.autoCode,"field":field});
						$(this).focusEditor(field);
					}
				},
				onBeforeLoad :function(rowData,param){
					$(this).removeData("deleteData");
					if (opts.onBeforeLoad) return opts.onBeforeLoad.call(target,rowData,param);
				}
			}));
		} else {
			$(target).datagrid($.extend({}, opts, {
				ctrlSelect:true,
				checkOnSelect:!opts.editing,
				onLoadSuccess:function(data) {
					/*为datagrid添加合并相同值的单元格*/
					if (opts.mergeable) {
						$(target).edatagrid("mergeEqualsCells");
					}
					/*为datagrid添加选择框被点击事件*/
					$(target).datagrid("getPanel").find("input[type='checkbox']").click(function(){
						//如果shift被按住，进行多选操作，_shiftisdown是在body元素键盘事件中被定义的全局变量
						if(typeof _shiftisdown != "undefined" && _shiftisdown) {
							var onshiftisdownrownum = null;//shift选择前的选中行号
							//判断是否有之前被选择的行，如果有获取最后一行的索引值
							var list = $(target).datagrid("getSelections");
							if(list.length > 0) {
								var last_index = null;
								for(var i=0; i<list.length; i++) {
									if(last_index !== null) {
										var new_index = $(target).datagrid("getRowIndex",list[i]);
										if(new_index > last_index) {
											last_index = new_index;
										}
									} else {
										last_index = $(target).datagrid("getRowIndex",list[i]);
									}
								}
								onshiftisdownrownum = last_index;
							}
							if(onshiftisdownrownum != null) {
								//根据input元素父元素tr的datagrid-row-index获取被点击行的索引
								var index = parseInt($(this).parents("tr[datagrid-row-index]").attr("datagrid-row-index"));
								//如果之前被选择的行索引在现在被选择的行索引之前，将两者之间的行进行选择
								if(onshiftisdownrownum < index) {
									for(var i=onshiftisdownrownum; i<index; i++) {
										$(target).datagrid("checkRow",i);
									}
								}
							}
						}
					});
					if (opts.onLoadSuccess) opts.onLoadSuccess.call(target, data);
				},
				//当发生拖动事件后，将对cookie进行修改
				onResizeColumn:function(field, width) {
					if(opts.url) {
						var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
						var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
						urlid = urlid.substring(0, myindex);
						urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
						var acookie = readCookie('_colwidth_' + urlid);
						if(acookie) {
							var values = JSON.parse(acookie);
							var mark = true;
							for(var i in values) {
								if(values[i].field == field) {
									values[i].width = width;
									mark = false;
									break;
								}
							}
							if(mark){
								values.push({"field":field,"width":width});
							}
							createCookie('_colwidth_' + urlid, JSON.stringify(values), 1000);
						} else {
							createCookie('_colwidth_' + urlid, '[{"field":"'+field+'","width":'+width+'}]', 1000);
						}
					} else {
						var baseUrl = (target.baseURI || document.URL);
						var urlid = baseUrl.substring(baseUrl.indexOf("entityName=")+11, baseUrl.length);
						var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
						urlid = urlid.substring(0, myindex);
						urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
						urlid = urlid + "_" + target.id;
						var acookie = readCookie('_colwidth_' + urlid);
						if(acookie) {
							var values = JSON.parse(acookie);
							var mark = true;
							for(var i in values) {
								if(values[i].field == field) {
									values[i].width = width;
									mark = false;
									break;
								}
							}
							if(mark){
								values.push({"field":field,"width":width});
							}
							createCookie('_colwidth_' + urlid, JSON.stringify(values), 1000);
						} else {
							createCookie('_colwidth_' + urlid, '[{"field":"'+field+'","width":'+width+'}]', 1000);
						}
					}
				},
				onClickCell:function(index,field){
					if(opts.editing) _isCheckFlag_ = false;
					if (opts.editing || (opts.editRowMap && opts.editRowMap[index.toString()])){
						//$(this).edatagrid('editRow', index);
						$(this).edatagrid('editCol',{"index":index,"field":field});
						$(this).focusEditor(field);
					}
				},
				onAfterCellEdit: function(index,field,row){
					opts.editIndex = undefined;
					var url = row.isNewRecord ? opts.saveUrl : opts.updateUrl;
					if (url){
						$.post(url, row, function(data){
							data.isNewRecord = null;
							$(target).datagrid('updateRow', {
								index: index,
								row: data
							});
							if (opts.tree){
								var t = $(opts.tree);
								var node = t.tree('find', row.id);
								if (node){
									node.text = row[opts.treeTextField];
									t.tree('update', node);
								} else {
									var pnode = t.tree('find', row[opts.treeParentField]);
									t.tree('append', {
										parent: (pnode ? pnode.target : null),
										data: [{id:row.id,text:row[opts.treeTextField]}]
									});
								}
							}
							opts.onSave.call(target, index, row);
						},'json');
					}
					if (opts.onAfterEdit) opts.onAfterEdit.call(target, index, row);
					//$(target).datagrid("unselectRow",index);
				},
				onCancelEdit: function(index, row){
					opts.editIndex = undefined;
					// by GaoXJ 2012-06-03
					/*if (row.isNewRecord) {
						$(this).datagrid('deleteRow', index);
					}*/
					if (opts.onCancelEdit) opts.onCancelEdit.call(target, index, row);
					//$(target).datagrid("unselectRow",index);
				},
				onBeforeLoad: function(param) {
					//$(this).datagrid('rejectChanges');
					$(this).edatagrid('clearColumnFilter');//清除过滤数据字段缓存
					if (opts.tree){
						var node = $(opts.tree).tree('getSelected');
						param[opts.treeParentField] = node ? node.id : undefined;
					}
					if (opts.onBeforeLoad) opts.onBeforeLoad.call(target, param);
				},
				onSelect : function(rowIndex, rowData) {
					if($(target).data("copyToClipboardType") == "col") {
						$(target).datagrid("getPanel").panel("panel").find("tr").removeClass("datagrid-row-selected");
						var allColumnFields = $(target).datagrid('getColumnFields',true).concat($(target).datagrid('getColumnFields'));
						for(var i in allColumnFields) {
							var field = allColumnFields[i];
							var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
							if($(menuName).length) {
								var __target;
								$(menuName).children().each(function() {
									if($(this).find("span").attr("isSelCol")) {
										__target = $(this);
									}
								});
								$(menuName).menu('setIcon', {
									target: __target,
									iconCls: 'tree-checkbox0'
								});
							}
						}
					}
					$(target).data("copyToClipboardType", "row");
					//if (opts.onSelect) opts.onSelect.call(target, rowIndex, rowData);
					if (opts.editing && !_isCheckFlag_) {
						_isCheckFlag_ = true;
						 $(target).datagrid("unselectRow", rowIndex);
					}
				},
				onUnselect : function(rowIndex, rowData) {
					if (opts.editing && !_isCheckFlag_) {
						_isCheckFlag_ = true;
						 $(target).datagrid("selectRow", rowIndex);
					}
				},
				onCheck : function(rowIndex, rowData) {
					jwpf.reloadDataGridFooter && jwpf.reloadDataGridFooter($(target), true); //重新计算选中值
				},
				onUncheck : function(rowIndex, rowData) {
					jwpf.reloadDataGridFooter && jwpf.reloadDataGridFooter($(target), true); //重新计算选中值
				},
				onCheckAll : function(rows) {
					jwpf.reloadDataGridFooter && jwpf.reloadDataGridFooter($(target), true); //重新计算选中值
				},
				onUncheckAll : function(rows) {
					jwpf.reloadDataGridFooter && jwpf.reloadDataGridFooter($(target), true); //重新计算选中值
				},
				onHeaderContextMenu: function(e, field) {
					var fldOpt = $(this).datagrid("getColumnOption", field);
					$(target).data("columnField", field); // 添加右键所在列的标识到datagrid
					if(fldOpt) {
						e.preventDefault();
						if(fldOpt.isFilterData) {//创建过滤菜单
							//获取or设置原始rows
							var rows = $(this).data("baseRows");
							if (!rows || rows.length == 0) {
								rows = $(this).datagrid("getRows");
								$(this).data("baseRows", rows);
							}
							if(rows.length) {
								var values = {},currentValues = {};
								//获取当前右击列所在数据，组装成一个以列值为键的对象
								$.each(rows,
								function(i, v) {
									if(v[field]!==undefined && v[field]!==null && v[field]!=="") {
										if(fldOpt.formatter) {
											values[v[field]] = fldOpt.formatter(v[field], v, i);
										} else {
											values[v[field]] = v[field].toString();
										}
									} else {
										values[""] = "空白";
									}
								});
								//创建右键列菜单
								var dgTarget = $(this);
								var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
								if ($(menuName).length == 0) {
									createColumnMenu(field, values, dgTarget, true);
								}
								//获取当前过滤之后该列存在的数据
								var currentRows = $(this).datagrid("getRows");
								$.each(currentRows,
								function(i, v) {
									if(v[field]!==undefined && v[field]!==null && v[field]!=="") {
										if(fldOpt.formatter) {
											currentValues[v[field]] = fldOpt.formatter(v[field], v, i);
										} else {
											currentValues[v[field]] = v[field].toString();
										}
									} else {
										currentValues[""] = "空白";
									}
								});
								//判断已有列菜单中是否存在已经过滤的数据
								var m = $(menuName);
								$.each(values, function(k, v) {
									var item = m.menu('findItem', v);
									if(item) {
										if (!currentValues[k]) { //不存在就设置当前的icon为未选中状态
											m.menu('setIcon', {
												target: item.target,
												iconCls: 'tree-checkbox0'
											});
											dgTarget.data("distic")[field][k] = v; //在当前列的过滤记录中记录当前已经过滤的数据名称
										} else if (dgTarget.data("distic")[field][k]) { //存在就设置当前的icon为选中状态
											m.menu('setIcon', {
												target: item.target,
												iconCls: 'tree-checkbox1'
											});
											delete dgTarget.data("distic")[field][k]; //在当前列的过滤记录中删除当前已经过滤的数据名称
										}
									}
								});
								var icon = 'tree-checkbox0';//未选中
								if ($.isEmptyObject(dgTarget.data("distic")[field])) { //判断当前列是否全部选中
									icon = 'tree-checkbox1';
								}
								var item = m.menu('findItem', "全选");
								m.menu('setIcon', {
									target: item.target,
									iconCls: icon
								});
								//显示列选择数据菜单
								m.menu('show', {
									left: e.pageX,
									top: e.pageY
								});
							}
						} else {//创建选中单列和复制列菜单
							var dgTarget = $(this);
							var menuName = '#_dg_' + $(this).attr("id") + '_tmenu_' + field;
							if ($(menuName).length == 0) {
								createColumnMenu(field, values, dgTarget, false);
							}
							$(menuName).menu('show', {
								left: e.pageX,
								top: e.pageY
							});
						}
					}
					if(opts.onHeaderContextMenu) opts.onHeaderContextMenu.call(target,e,field);
				}
			}));
			//添加shift事件
			$(target).datagrid("getPanel").keydown(function(event){
				switch(event.keyCode) {
					case 16:_shiftisdown=true;//是否按住shift
				}
			}).keyup(function(event){
				switch(event.keyCode) {
					case 16:_shiftisdown=false;
				}
			});
//		var a = [1,2,3];
//		a.push("c");
//		createCookie('_dg_' + $(target).attr("id"),a,365);
//		console.log(readCookie('_dg_' + $(target).attr("id")));
		//读cookie是否有当前data的设置
//		var acookie = readCookie('_dg_' + $(target).attr("id"));
//		if(acookie != ""){
			//将cookie转成数组
//			while(acookie.length!=0){
//		 		var end = acookie.indexOf(",",0);
//		 		if(end!=-1){
//		 			console.log(acookie.substring(0,end));
//		 			var x = JSON.parse(acookie.substring(0,end));
//		 			if(x.hidden){
//		 				$(target).edatagrid('hideColumn',x.field);
//		 			}
//		 			acookie = acookie.substring(end+1,acookie.length);
//		 		}
//		 		else{
//		 			console.log(acookie);
//		 			var x = JSON.parse(acookie);
//		 			if(x.hidden){
//		 				$(target).edatagrid('hideColumn',x.field);
//		 			}
//		 			acookie = "";
//		 		}
//			}
			
			//var xx = JSON.parse(readCookie('_dg_' + $(target).attr("id")));
			//console.log(xx[0]);
			//根据cookie中的设置去控制咧的显隐
			
//		}
		
		//$.cookie('_dg_' + $(target).attr("id"));
		//console.log($.cookie('_dg_' + $(target).attr("id")));
		//$(target).edatagrid('hideColumn','ck');
		
		}
		if(opts.url) {
			var urlid = opts.url.substring(opts.url.indexOf("entityName=")+11, opts.url.length);
			var myindex = urlid.indexOf("&")===-1?urlid.length:urlid.indexOf("&");
			urlid = urlid.substring(0, myindex);
			urlid = urlid.replace(/[.]/g,"_");//当前data页的标识
			var acookie = readCookie('_dg_' + urlid);
			if(acookie) {
				//将cookie转成数组,根据cookie中的设置去控制咧的显隐
				var values = JSON.parse(acookie);
				var ColumnFields = $(target).edatagrid('getColumnFields',true).concat($(target).edatagrid('getColumnFields'));
				for(var i in values){
					if(values[i].hidden){
						var _field = values[i].field;
						//如果字段没有在设计器中被删，使用datagrid方法隐藏该字段
						for (var i in ColumnFields) {
							if(ColumnFields[i]==_field){
								$(target).datagrid('hideColumn',_field);
								$(target).datagrid('resize');
								break;
							}
						}
					}
				}
			}
			//右键设置列显示
			$(target).edatagrid('getPanel').panel('panel').find("div.datagrid-header-rownumber").parent("td").bind("contextmenu",function(e){
				//e.preventDefault();
				//if(e.which==3) // 1 = 鼠标左键 left; 2 = 鼠标中键; 3 = 鼠标右键 
				//{
				var values = [];//与cookie中的数组相同
				var menuName = '#_dg_' + $(target).attr("id") + '_tmenu_' + urlid;
				//如果没有menu，就创建一个新的
				if ($(menuName).length == 0) {
					var acookie = readCookie('_dg_' + urlid);
					$(target).edatagrid('getColumnFields');
					//拼接固定字段与非固定字段
					var ColumnFields = $(target).edatagrid('getColumnFields',true).concat($(target).edatagrid('getColumnFields'));
					for (var i in ColumnFields) {
						var a = $(target).edatagrid('getColumnOption',ColumnFields[i]);
						//创建一个记录设置的数组
						var value = {field:ColumnFields[i],hidden:false};
						if(a.title) {
							values.push(value);
						}
					}
					if(acookie) {
						//将cookie转成数组,根据cookie中的设置去控制咧的显隐
						var values_ = JSON.parse(acookie);
						for(var i in values_) {
							for(var j in values) {
								if(values[j].field === values_[i].field) {
									values[j].hidden = values_[i].hidden;
								}
							}
						}
					}
					//如果没有 menuName的Menu就创建一个
					//改为根据页面高度，动态设定列显隐控制菜单的高度
					createColScreenMenu(values, $(target), e, urlid);
				}
				$(menuName).menu('show', {
					left: e.pageX,
					top: e.pageY
				});
				//e.preventDefault();
				//e.stopPropagation();
				return false;
//				}
			});
		}
		
		/**
		* 创建列数据菜单
		* @param values 列属性数组
		* @param target 目标datagrid
		**/
		function createColScreenMenu(values, target, e, urlid) {
			var dgId = target.attr("id");
			var menuName = '_dg_' + dgId + '_tmenu_' + urlid;
			var height = $(window).height() - e.pageY - 50;
			var tmenu;
			if(values.length*22>height) {
				tmenu = $('<div id="' + menuName + '" class="easyui-menu easyui-panel _dg_tmenu_' + dgId + '" style="width:250px;height:' + height + 'px"></div>').appendTo('body');
			}else{
				tmenu = $('<div id="' + menuName + '" class="easyui-menu easyui-panel _dg_tmenu_' + dgId + '" style="width:250px"></div>').appendTo('body');
			}
			$('<div iconCls="tree-checkbox1"/>').html("<span isSelAll='true'>全选</span>").appendTo(tmenu);
			$('<div class="menu-sep"/>').appendTo(tmenu);
			for(var i in values) {
				var x = target.edatagrid('getColumnOption',values[i].field);
				var iconCls;
				if(values[i].hidden){
					iconCls = "tree-checkbox0";
				}else{
					iconCls = "tree-checkbox1";
				}
				var sp = "<span keyVal='" + values[i].field + "'>" + x.title + "</span>";
				$('<div iconCls="'+iconCls+'"/>').html(sp).appendTo(tmenu);
			}
			//实例化数据列选择菜单
			//menu显示滚动条，修改滚动条无法拖动。
			var scrollbarisonmousedown = false;
			tmenu.mousedown(function(){
				scrollbarisonmousedown = true;
			});
			tmenu.panel({});
			tmenu.menu({
				onHide : function() {
					if(scrollbarisonmousedown) {
						tmenu.menu('show');
					}
					scrollbarisonmousedown = false;
				},
				onClick: function(item) {
					var spObj = $(item.target).find("span");
					var itemVal = spObj.attr("keyVal");
					var isSelAll = false;
					if(spObj.attr("isSelAll")) {
						isSelAll = true;
					}
					if (isSelAll) {//全选
						if(item.iconCls == 'tree-checkbox0') { //全选
							var items = $(item.target).nextAll(".menu-item");
							$.each(items,
							function(k, v) {
								var disticItem = tmenu.menu('findItem', v);
								tmenu.menu('setIcon', {
									target: v,
									iconCls: 'tree-checkbox1'
								});
							});
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox1'
							});
							//将所有列显示
							for(i in values) {
								values[i].hidden = false;
								$(target).edatagrid('showColumn',values[i].field);
							}
						} else if(item.iconCls == 'tree-checkbox1'){ //全不选
							var items = $(item.target).nextAll(".menu-item");
							$.each(items, function(k,v) {
								var sp = $(v).find("span");
								var iv = sp.attr("keyVal");
								var itemName = sp.text();
								tmenu.menu('setIcon', {
									target: v,
									iconCls: 'tree-checkbox0'
								});
							});
							tmenu.menu('setIcon', {
								target: item.target,
								iconCls: 'tree-checkbox0'
							});
							//将所有列隐藏
							for(i in values){
								values[i].hidden = true;
								$(target).edatagrid('hideColumn',values[i].field);
								$(target).edatagrid('resize');
							}
						}
					} else if (!isSelAll && item.iconCls == 'tree-checkbox1') {
						//选中状态去除，即过滤
						tmenu.menu('setIcon', {
							target: item.target,
							iconCls: 'tree-checkbox0'
						});
						//隐藏一列
						for(i in values){
							if(values[i].field==itemVal){
								values[i].hidden = true;
								break;
							}
						}
						$(target).edatagrid('hideColumn',itemVal);
						$(target).edatagrid('resize');
					} else if (!isSelAll) {//取消过滤
						tmenu.menu('setIcon', {
							target: item.target,
							iconCls: 'tree-checkbox1'
						});
						//显示一列
						for(i in values){
							if(values[i].field==itemVal){
								values[i].hidden = false;
								break;
							}
						}
						$(target).edatagrid('showColumn',itemVal);
					}
					//刷新menu
					tmenu.menu('show');
					$(target).edatagrid('fixColumnSize');
					var valuesstr = JSON.stringify(values);
					createCookie('_dg_' + urlid,valuesstr,1000);
				}
			});
		}
		
		/*复制datagrid行或列数据到剪贴板，返回Excel格式数据*/
		function doCopyToClipboard() {
			var __panel = $(target).datagrid("getPanel").panel("panel");
			var length = $(target).datagrid('getRows').length;
			var rows = [];
			if($(target).data("copyToClipboardType") == "row") {
				for(var i=0; i<length; i++) {
					var __tr = __panel.find("tr.datagrid-row-checked[datagrid-row-index="+i+"]");
					if(__tr.length) {
						var row = [];
						__tr.each(function(i) {
							$(this).find("td:visible div:not(.datagrid-cell-rownumber)").each(function() {
								if($(this).children().length === 0) {
									row.push($(this).text());
								}
							});
						});
						rows.push(row);
					}
				}
			} else if($(target).data("copyToClipboardType") == "col") {
				for(var i=0; i<length; i++) {
					var __tr = __panel.find("tr[datagrid-row-index="+i+"]");
					if(__tr.length) {
						var row = [];
						__tr.each(function(i) {
							$(this).find("td.datagrid-row-selected:visible div:not(.datagrid-cell-rownumber)").each(function() {
								if($(this).children().length === 0) {
									row.push($(this).text());
								}
							});
						});
						rows.push(row);
					}
				}
			}
			var rowsdata = [];
			if(rows && rows.length) {
				for(var i in rows) {
					rowsdata.push(rows[i].join("\t"));
				}
			}
			return rowsdata.join("\n");
		}
		
		/*选中将复制到剪贴板的列*/
		function selectColumnToClipboard() {
			if($(target).data("copyToClipboardType")=="row") {
				$(target).datagrid("unselectAll");
			}
			$(target).data("copyToClipboardType","col");
			var field = $(target).data("columnField");
			$(target).datagrid("getPanel").panel("panel").find("td[field=" + field + "]").addClass("datagrid-row-selected");
		}
		
		/*取消选中将复制到剪贴板的列*/
		function unSelectColumnToClipboard() {
			var field = $(target).data("columnField");
			$(target).datagrid("getPanel").panel("panel").find("td[field=" + field + "]").removeClass("datagrid-row-selected");
		}
		
		/**
		* 创建列数据菜单
		* @param field 当前列
		* @param values 当期列组成的以数据为键的对象
		* @param target 目标datagrid
		* @param isFilter 显示过滤列
		**/
		function createColumnMenu(field, values, target, isFilter) {
			var dgId = target.attr("id");
			var menuName = '_dg_' + dgId + '_tmenu_' + field;
			var tmenu = $('<div id="' + menuName + '" class="_dg_tmenu_' + dgId
							+ '" style="width:250px;"></div>').appendTo('body');
			$('<div iconCls="tree-checkbox0"/>').html(
					"<span isNotFilter='true' isSelCol='true'>选中列</span>")
					.appendTo(tmenu);
			$('<div iconCls="icon-copy" title="复制选中的行或列"/>')
					.html("<span isNotFilter='true' isCopy='true'>复制选中的行或列</span>")
					.appendTo(tmenu);
			if (dgId != "queryList" && opts.editing) {
				$('<div iconCls="icon-paste" title="粘帖列"/>').html(
						"<span isNotFilter='true' isPaste='true'>粘帖列</span>")
						.appendTo(tmenu);
			}
			if (isFilter) {
				$('<div class="menu-sep"/>').appendTo(tmenu);
				$('<div iconCls="tree-checkbox1"/>').html(
						"<span isSelAll='true'>全选</span>").appendTo(tmenu);
				$('<div class="menu-sep"/>').appendTo(tmenu);
				$.each(values, function(key, value) {
					var sp = "<span keyVal='" + key + "' title='" + value + "'>" + value + "</span>";
					$('<div iconCls="tree-checkbox1"/>').html(sp).appendTo(tmenu);
				});
				var disObj = target.data("distic");// 初始化，已过滤数据存储对象
				if (disObj) {
					disObj[field] = {};
				} else {
					var obj = {};
					obj[field] = {};
					target.data("distic", obj);
				}
				// tmenu.data("distic", {});
			}
			// 实例化数据列选择菜单
			tmenu.menu({
				onShow : function() {
					/*var menuObj = this;
					var obj = $("div[iconCls='icon-copy']", menuObj);// div[iconCls='icon-paste']
					var _zcClient_ = new ZeroClipboard(obj[0]);
					_zcClient_.on('ready', function(event) {
						_zcClient_.on('copy', function(event) {
							var data = doCopyToClipboard();
							event.clipboardData.setData('text/plain',
									data);
							// console.log("111");
						});

						_zcClient_.on('aftercopy', function(event) {
							// console.log('Copied text to clipboard: '
							// + event.data['text/plain']);
							alert("已复制到剪切板！");
							ZeroClipboard.destroy();
						});
					});
					_zcClient_.on('error', function(e) {
						console.log("error:");
						console.log(e);
					});*/
					
				},
				onClick : function(item) {
					var spObj = $(item.target).find("span");
					var itemVal = spObj.attr("keyVal");
					if (spObj.attr("isNotFilter")) {
						// 选中列或复制列
						if (spObj.attr("isSelCol")) {// 选中列事件
							if (item.iconCls == 'tree-checkbox0') {
								// TODO 选中列，下面添加选中方法
								selectColumnToClipboard();
								tmenu.menu('setIcon', {
									target : item.target,
									iconCls : 'tree-checkbox1'
								});
							} else if (item.iconCls == 'tree-checkbox1') {
								// TODO 取消选中列，下面添加取消选中方法
								unSelectColumnToClipboard();
								tmenu.menu('setIcon', {
									target : item.target,
									iconCls : 'tree-checkbox0'
								});
							}
						}
						/*
						 * if(spObj.attr("isCopy")) {//复制列
						 *  }
						 */
						if (spObj.attr("isPaste")) {// 粘帖列
							/*
							 * var gridPanel =
							 * target.edatagrid('getPanel').panel('panel');
							 * var gridBody =
							 * gridPanel.find("div.datagrid-body"); var
							 * e = jQuery.Event("mousedown");
							 * e.which=86,e.ctrlKey=true;
							 * gridBody.trigger(e);
							 */
							alert("请使用Ctrl+V粘贴数据！");
						}
					} else {// 过滤字段
						var isSelAll = false;
						if (spObj.attr("isSelAll")) {
							isSelAll = true;
						}
						if (isSelAll) {// 全选
							if (item.iconCls == 'tree-checkbox0') { // 全选
								$.each(
									target.data("distic")[field],
									function(k, v) {
										var disticItem = tmenu.menu('findItem',v);
										tmenu.menu('setIcon',{
											target : disticItem.target,
											iconCls : 'tree-checkbox1'
										});
								});
								target.data("distic")[field] = {};
								tmenu.menu('setIcon', {
									target : item.target,
									iconCls : 'tree-checkbox1'
								});
								dataFilter(field, target);
							} else if (item.iconCls == 'tree-checkbox1') { // 全不选
								var items = $(item.target).nextAll(".menu-item");
								$.each(items, function(k, v) {
									var sp = $(v).find("span");
									var iv = sp.attr("keyVal");
									var itemName = sp.text();
									tmenu.menu('setIcon',
										{
											target : v,
											iconCls : 'tree-checkbox0'
										});
									target.data("distic")[field][iv] = itemName;
								});
								tmenu.menu('setIcon', {
									target : item.target,
									iconCls : 'tree-checkbox0'
								});
								dataFilter(field, target);
							}
						} else if (!isSelAll
								&& item.iconCls == 'tree-checkbox1') {//选中状态去除，即过滤
							target.data("distic")[field][itemVal] = item.text;
							tmenu.menu('setIcon', {
								target : item.target,
								iconCls : 'tree-checkbox0'
							});
							dataFilter(field, target);
						} else if (!isSelAll) {//取消过滤
							delete target.data("distic")[field][itemVal];
							tmenu.menu('setIcon', {
								target : item.target,
								iconCls : 'tree-checkbox1'
							});
							dataFilter(field, target);
						}
						tmenu.menu('show');
					}
				}
			});
			//clipboard.js no flash
			var obj = $("div[iconCls='icon-copy']", tmenu);
			var clipboard = new ClipboardJS(obj[0], {
			    // 点击copy按钮，直接通过text直接返回复印的内容
			    text: function(trigger) {
			    	var result = doCopyToClipboard();
			    	//console.log(result);
			    	return result;
			    }
			});

			clipboard.on('success', function(e) {
				console.log(e);
				//console.log(e.text);
				alert("已复制到剪切板！");
			});

			clipboard.on('error', function(e) {
			    console.log(e);
			    alert("复制失败，请尝试重新复制！");
			});
		}

		/**
		 * 从原始rows中过滤数据
		 * 
		 * @param field 当前列
		 * @param target 目标datagrid
		 */
		function dataFilter(field, target) {
			var newRows = target.data("baseRows");
			var temp = [];
			var disticValue = target.data('distic');
			var isEmptyObj = true;
			$.each(disticValue, function(k, v) {
				isEmptyObj = isEmptyObj && $.isEmptyObject(v);
			});
			if (isEmptyObj) {
				temp = newRows;
			} else {
				$.each(newRows, function(k, v) {
					var isNotFilter = true;
					$.each(disticValue, function(fld, obj) {
						isNotFilter = isNotFilter && !obj[v[fld]];
					});
					if (isNotFilter) {
						temp.push(v);
					}
				});
			}
			target.datagrid("loadData", temp);
		}
		
		function numbox(_a, _b) {
			var _c = $.data(_a, "numberbox");
			var _d = _c.options;
			var _e = _c.field.val();
			_b = _d.parser.call(_a, _b);
			_d.value = _b;
			_c.field.val(_b);
			// $(_a).val(_d.formatter.call(_a,_b));
			if (_e != _b) {
				_d.onChange.call(_a, _b, _e);
			}
			// $(_a).val(_d.formatter.call(_a,_e));
		};

		/**
		 * 查找上一个或下一个可编辑单元格
		 */
		function findPreOrNextEditableField(td, isPrev) {
			var nextTd = null;
			if (isPrev) {
				nextTd = td.prev("td[field]");
				// 从非固定列跨至固定列
				if (!nextTd.length) {
					var columnfields = $(target).datagrid("getColumnFields",
							true);
					var fields = $(target).datagrid("getColumnFields");
					if ($.inArray(td.attr("field"), fields) >= 0
							&& columnfields.length) {
						for ( var i = 0; i < fields.length; i++) {
							var nfOpt = $(target).datagrid("getColumnOption",
									columnfields[columnfields.length - i - 1]);
							if (nfOpt && !nfOpt.hidden && nfOpt.editor
									&& nfOpt.editor.type
									&& nfOpt.editor.options
									&& !nfOpt.editor.options.readonly
									&& !nfOpt.editor.options.disabled) {
								nextTd = {
									length : 1,
									attr : function() {
										return columnfields[columnfields.length
												- i - 1];
									}
								};
								return nextTd;
							}
						}
					}
				}
			} else {
				nextTd = td.next("td[field]");
				// 从固定列跨至非固定列
				if (!nextTd.length) {
					var columnfields = $(target).datagrid("getColumnFields",
							true);
					var fields = $(target).datagrid("getColumnFields");
					if ($.inArray(td.attr("field"), columnfields) >= 0
							&& fields.length) {
						for ( var i = 0; i < fields.length; i++) {
							var nfOpt = $(target).datagrid("getColumnOption",
									fields[i]);
							if (nfOpt && !nfOpt.hidden && nfOpt.editor
									&& nfOpt.editor.type
									&& nfOpt.editor.options
									&& !nfOpt.editor.options.readonly
									&& !nfOpt.editor.options.disabled) {
								nextTd = {
									length : 1,
									attr : function() {
										return fields[i];
									}
								};
								return nextTd;
							}
						}
					}
				}
			}
			if (nextTd.length) {
				var nextField = nextTd.attr("field");
				var nfOpt = $(target).datagrid("getColumnOption", nextField);
				if (nextTd.is(":visible")) {
					if (nfOpt && nfOpt.editor) {
						var edtType = nfOpt.editor.type;
						var edtOpt = nfOpt.editor.options;
						if (edtType && edtOpt) {
							if (edtOpt.readonly || edtOpt.disabled) {
								return findPreOrNextEditableField(nextTd,
										isPrev);
							} else {
								return nextTd;
							}
						} else {
							return findPreOrNextEditableField(nextTd, isPrev);
						}
					} else {
						return findPreOrNextEditableField(nextTd, isPrev);
					}
				} else {
					if (nfOpt && !nfOpt.hidden) {
						return nextTd;
					} else {
						return findPreOrNextEditableField(nextTd, isPrev);
					}
				}
			} else {
				return nextTd;
			}
		};
		
        function keyCtr() {
			var grid = $(target);
			var opts = $.data(target, 'edatagrid').options;
			grid.edatagrid('getPanel').panel('panel').unbind('keydown');
			grid.edatagrid('getPanel').panel('panel').bind('keydown', function (e) {	
				/*在这里阻止冒泡是因为针对主表控件选择的keydown事件挂在了整个表单上 ，修复主表事件监听不合理性后，可取消此处不必要的冒泡拦截*/
				e.stopPropagation();
				e.Handled = true;
				if(opts.tree) {				
					switch (e.keyCode) {
						case 38: // up
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var index = td.parent().attr("node-id");
							var upIndex = "";
							var currentParent = grid.treegrid('getParent',index);
							if(currentParent){
								var childList =currentParent.children;
								for(var i=0;i<childList.length;i++){
									if(childList[i].autoCode==index){
										if(i-1>=0){
											upIndex = childList[i-1].autoCode;
										}else{
											upIndex = currentParent.autoCode;
										}
									}
								}
							}else{
								var roots =  grid.treegrid('getRoots',index);
								for(var j=0;j<roots.length;j++){
									if(roots[j].autoCode==index){
										if(j-1>=0){
											upIndex = roots[j-1].autoCode;
										}else{
											upIndex = roots[j].autoCode;
										}
									}
								}
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if (index && (opts.editing || (opts.editRowMap && opts.editRowMap[upIndex])) 
									&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : upIndex,
									"field" : field
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.edatagrid('endCellEdit', editOpt);
								grid.edatagrid('beginCellEdit', opt);
								opts.editIndex = opt.index;
								opts.editCol = field;
								grid.focusEditor(field);
							}
							break;
						case 40: // down
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var index = td.parent().attr("node-id");
							var downIndex = "";
							var currentChild = grid.treegrid('getChildren',index);
							var currentParent = grid.treegrid('getParent',index);
							if(currentChild && currentChild.length>0){
								downIndex = currentChild[0].autoCode;
							}else if(currentParent){
								var childList =currentParent.children;
								for(var i=0;i<childList.length;i++){
									if(childList[i].autoCode==index){
										if(i+1<childList.length){
											downIndex = childList[i+1].autoCode;
										}else{
											var pcode = index.substring(0,4);
											var roots =  grid.treegrid('getRoots',pcode);
											for(var j=0;j<roots.length;j++){
												if(roots[j].autoCode==pcode){
													if(j+1<roots.length){
														downIndex= roots[j+1].autoCode;
													}
												}
											}
										
										}
									}
								}
							}else if(currentChild && currentChild.length<=0){
								var roots =  grid.treegrid('getRoots',index);
								for(var j=0;j<roots.length;j++){
									if(roots[j].autoCode==index){
										if(j+1<roots.length){
											downIndex= roots[j+1].autoCode;
										}else{
											downIndex = roots[j].autoCode;
										}
									}
								}
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if ((opts.editing || (opts.editRowMap && opts.editRowMap[downIndex])) 
									&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : downIndex,
									"field" : field
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.edatagrid('endCellEdit', editOpt);
								grid.edatagrid('beginCellEdit', opt);
								opts.editIndex = opt.index;
								opts.editCol = field;
								grid.focusEditor(field);

							}
							break;
						case 37: // left
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var prevTd = findPreOrNextEditableField(td, true);
							var num = prevTd.length;
							var newField = prevTd.attr("field");
							var index = td.parent().attr("node-id");
							if (num != 0
									&& (e.target.readOnly /*若焦点中的input为只读，移动时不需要关心光标位置*/
										|| $(e.target).getSelectionStart() == 0)
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if ($.data(e.target, "numberbox")) {
									numbox(e.target, $(e.target).val());
								}
								var opt = {
									"index" : index,
									"field" : newField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.edatagrid('endCellEdit', editOpt);
								grid.edatagrid('beginCellEdit', opt);
								opts.editIndex = opt.index;
								opts.editCol = newField;
								grid.focusEditor(newField);

							}
							break;
						case 39: // right
							var td = $(e.target).closest("td[field]");
							var valLength = $(e.target).val().length;
							var field = td.attr("field");
							var nextTd = findPreOrNextEditableField(td);
							var num = nextTd.length;
							var newField = nextTd.attr("field");
							var index = parseInt(td.parent().attr("node-id"));
							if (num != 0
									&& $(e.target).getSelectionStart() == valLength
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if ($.data(e.target, "numberbox")) {
									numbox(e.target, $(e.target).val());
								}
								var opt = {
									"index" : index,
									"field" : newField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.edatagrid('endCellEdit', editOpt);
								grid.edatagrid('beginCellEdit', opt);
								opts.editIndex = opt.index;
								opts.editCol = newField;
								grid.focusEditor(newField);
							}
							break;
						case 9: // Tab					
							if(e.ctrlKey){
								var td = $(e.target).closest("td[field]");
								var index = parseInt(td.parent().attr("node-id"));
								var rowData = grid.treegrid("find",index);
								grid.edatagrid("insertNewRow",rowData);
							}else{
							var td = $(e.target).closest("td[field]");
							var field = td.attr("field");
							var nextTd = findPreOrNextEditableField(td);
							var num = nextTd.length;
							var nextField = nextTd.attr("field");
							var index = parseInt(td.parent().attr("node-id"));
							
							var currentData = grid.treegrid("find",index);
							var pCode = currentData.autoParentCode;
							var lastCode = "";
							var childList = [];
							var roots = [];
							if(pCode){//判断是字节点还是父节点
								var currentParent = grid.treegrid('getParent',index);
								childList =currentParent.children;
								lastCode = childList[childList.length-1].autoCode;
							}else{
								 roots =  grid.treegrid('getRoots',index);
								lastCode = roots[roots.length-1].autoCode;
							}
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							if (num != 0&& grid.edatagrid('validateCol',(e.target))) {
								var opt = {
									"index" : index,
									"field" : nextField
								};
								var editOpt = {
									"index" : index,
									"field" : field
								};
								grid.edatagrid('endCellEdit', editOpt);
								grid.edatagrid('beginCellEdit', opt);
								opts.editIndex = opt.index;
								opts.editCol = nextField;
								grid.focusEditor(nextField);
							}  else if (num == 0
									&& lastCode != index
									&& grid.edatagrid('validateCol',
											(e.target))) {
								var nextIndex = "";
								if(pCode){	
									for(var i=0;i<childList.length;i++){
										if(childList[i].autoCode==index){
											nextIndex = childList[i+1].autoCode;
											break;
										}
									}
								}else{
									for(var j=0;j<roots.length;j++){
										if(roots[j].autoCode==index){	
											nextIndex = roots[j+1].autoCode;
											break;
										}
									}
								}					
							
								if(opts.editing || (opts.editRowMap && opts.editRowMap[nextIndex])) {
									var firstField = opts.treeField;
									var opt = {
										"index" : nextIndex,
										"field" : firstField
									};
									var editOpt = {
										"index" : index,
										"field" : field
									};
									grid.edatagrid('endCellEdit', editOpt);
									grid.edatagrid('beginCellEdit', opt);
									opts.editIndex = opt.index;
									opts.editCol = firstField;
									grid.focusEditor(firstField);
								}
							}else if (num == 0
									&& lastCode == index
									&& grid.edatagrid('validateCol',
											(e.target))) {
								if(opts.editing) { //编辑模式下
									if(pCode){								
										grid.edatagrid("insertNewRow",currentParent);
									}else{			
										grid.edatagrid("addRow");
									}
								}
							} 
						}
						return false;
						break;	
					case 13: // enter
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						if(e.ctrlKey){
							var td = $(e.target).closest("td[field]");
							var index = parseInt(td.parent().attr("node-id"));
							var rowData = grid.treegrid("find",index);
							grid.edatagrid("insertNewRow",rowData);
						}else{
							if(opts.editing && grid.edatagrid('validateCol',
									(e.target))) {
								var td = $(e.target).closest("td[field]");
								var index = parseInt(td.parent().attr("node-id"));
								var currentData = grid.treegrid("find",index);
								var pCode = currentData.autoParentCode;
								if(pCode){								
									grid.edatagrid("insertNewRow",currentParent);
								}else{			
									grid.edatagrid("addRow");
								}
							}
						}
						break;
			    }
            } else {		
                switch (e.keyCode) {
					case 38: // up
						var td = $(e.target).closest("td[field]");
						var field = td.attr("field");
						var index = parseInt(td.parent().attr("datagrid-row-index"));
						index = parseInt(index);
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						if (index > 0 
								&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index-1).toString()])) 
								&& grid.edatagrid('validateCol', (e.target))) {
							var opt = {
								"index" : index - 1,
								"field" : field
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;
							opts.editCol = field;
							grid.focusEditor(field);
						}
						break;
					case 40: // down
						var td = $(e.target).closest("td[field]");
						var field = td.attr("field");
						var index = parseInt(td.parent().attr("datagrid-row-index"));
						var rows = grid.datagrid('getRows');
						var maxIndex = rows.length - 1;
						index = parseInt(index);
						maxIndex = parseInt(maxIndex);
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						var rowsapn = td.attr("rowspan")?parseInt(td.attr("rowspan")):1;
						if (maxIndex >= index + rowsapn
								&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index+1).toString()]))
								&& grid.edatagrid('validateCol',
										(e.target))) {
							var opt = {
								"index" : index + rowsapn,//加上rowspan就是，下移一个单元格
								"field" : field
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;//在beginCellEdit方法中，index可能发生变化
							opts.editCol = field;
							grid.focusEditor(field);
						} else if(maxIndex == index + rowsapn - 1
								&& opts.editing
								&& grid.edatagrid('validateCol',
										(e.target))) { //最后一行，新增行
							grid.edatagrid('addRow');
						}
						break;
					case 37: // left
						var td = $(e.target).closest("td[field]");
						var field = td.attr("field");
						//var prevTd = td.prev("td[field]");
						var prevTd = findPreOrNextEditableField(td, true);
						var num = prevTd.length;
						var newField = prevTd.attr("field");
						var index = parseInt(td.parent().attr("datagrid-row-index"));
						if (num != 0
								&& (e.target.readOnly /*若焦点中的input为只读，移动时不需要关心光标位置*/
									|| $(e.target).getSelectionStart() == 0)
								&& grid.edatagrid('validateCol',
										(e.target))) {
							/*修复数字控件无法用键盘移动的问题*/
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							var opt = {
								"index" : index,
								"field" : newField
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;
							opts.editCol = newField;
							grid.focusEditor(newField);

						}
						break;
					case 39: // right
						var td = $(e.target).closest("td[field]");
						var valLength = $(e.target).val().length;
						var field = td.attr("field");
						//var nextTd = td.next("td[field]");
						var nextTd = findPreOrNextEditableField(td);
						var num = nextTd.length;
						var newField = nextTd.attr("field");
						var index = parseInt(td.parent().attr("datagrid-row-index"));
						
						if (num != 0
								&& $(e.target).getSelectionStart() == valLength
								&& grid.edatagrid('validateCol',
										(e.target))) {
							/*修复数字控件无法用键盘移动的问题*/
							if ($.data(e.target, "numberbox")) {
								numbox(e.target, $(e.target).val());
							}
							var opt = {
								"index" : index,
								"field" : newField
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;
							opts.editCol = newField;
							grid.focusEditor(newField);
						}
						break;
					case 9: // tab键
						var td = $(e.target).closest("td[field]");
						var rowsapn = td.attr("rowspan")?parseInt(td.attr("rowspan")):1;
						var field = td.attr("field");
						//var nextTd = td.next("td[field]");
						var nextTd = findPreOrNextEditableField(td);
						var num = nextTd.length;
						var nextField = nextTd.attr("field");
						var rows = grid.datagrid('getRows');
						var maxIndex = rows.length - 1;
						var index = parseInt(td.parent().attr("datagrid-row-index"));
						maxIndex = parseInt(maxIndex);
						index = parseInt(index);
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						if (num != 0
								&& grid.edatagrid('validateCol',
										(e.target))) {
							
							var opt = {
								"index" : index,
								"field" : nextField
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;
							opts.editCol = nextField;
							grid.focusEditor(nextField);
						} else if (num == 0
								&& maxIndex > index
								&& (opts.editing || (opts.editRowMap && opts.editRowMap[(index+1).toString()]))
								&& grid.edatagrid('validateCol', (e.target))) {
							var columnfields = $(target).datagrid("getColumnFields", true);
							columnfields.length ? firstField = columnfields[1] : firstField = $(target).datagrid("getColumnFields")[0];
							var opt = {
								"index" : index + rowsapn,
								"field" : firstField
							};
							var editOpt = {
								"index" : index,
								"field" : field
							};
							grid.edatagrid('endCellEdit', editOpt);
							grid.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;
							opts.editCol = firstField;
							grid.focusEditor(firstField);
						} else if (opts.editing && num == 0
								&& maxIndex == index
								&& grid.edatagrid('validateCol', (e.target))) {
							grid.edatagrid('addRow');
						}
						break;
					case 13: //回车
						if ($.data(e.target, "numberbox")) {
							numbox(e.target, $(e.target).val());
						}
						if(opts.editing && grid.edatagrid('validateCol',
								(e.target))) {
							grid.edatagrid('addRow');
						}
						break;
					}
			 	}
			});
		}
		
		function pasteFromExcel() {
			var grid = $(target);
			var tableKey = grid.attr('id');
			var opts = $.data(target, 'edatagrid').options;
			var gridPanel = grid.edatagrid('getPanel').panel('panel');
			var gridBody = gridPanel.find("div.datagrid-body");
			// 表格粘贴
			gridBody.on('paste', function(e) {
				if (opts.editing) {
					if($(e.target).hasClass("datagrid-editable-input")) {return true;}
					var text;
					var clp = (e.originalEvent || e).clipboardData;
					if (clp === undefined || clp === null) {
						text = window.clipboardData.getData("text") || "";
					} else {
						//console.log("1:" + clp.getData('text/plain'));
						text = clp.getData('text/plain') || "";
						//console.log("_1:" + text);
						//console.log("_2:" + clp.getData('text/plain'));
					}
					if (text !== "" && text.indexOf("\t") >= 0) {
						e.preventDefault();
						// console.log(e);
						var startFieldName = $(e.target).parents("td[field]").attr("field");
						pasteTableFromClipboard(text, gridPanel, startFieldName);
						return false;
					}
				}
			});
			// 列粘贴
			var fieldHeader = gridPanel.find("div.datagrid-header td");
			fieldHeader.on('paste', function(e) {
				var fieldName = $(this).attr("field");
				if (opts.editing) {
					var text;
					var clp = (e.originalEvent || e).clipboardData;
					if (clp === undefined || clp === null) {
						text = window.clipboardData.getData("text") || "";
					} else {
						text = clp.getData('text/plain') || "";
					}
					if (text !== "" && text.indexOf("\r\n") >= 0) {
						e.preventDefault();
						// console.log(e);
						pasteColumnFromClipboard(text, fieldName);
						return false;
					}
				}
			});
		}

		/* 将剪贴板的内容复制到指定表格 */
		function pasteTableFromClipboard(text, gridPanel, startFieldName) {
			var arr = text.split("\r\n");
			var len = arr.length;
			if (arr[len - 1] === "") {
				len--;
			}
			if (len) {
				var fieldCols = [];
				gridPanel.find(".datagrid-header td[field]:not[field!='ck']:visible").each(function() {
					fieldCols.push($(this).attr("field"));
				});
				if(startFieldName) {
					fieldCols = fieldCols.slice(fieldCols.indexOf(startFieldName));
				}
				var rowData = [];
				for ( var i = 0; i < len - 1; i++) {
					var row = arr[i];
					do {
						var count = 0;
						for ( var j = 0; j < row.length; j++) {
							if (row.charAt(j) === "\"") {
								count++;
							}
						}
						if (count % 2) {
							i++;
							row = row + "<br/>" + arr[i];
						}
					} while (count % 2);
					var cols = row.split(/\t/);
					var rowObj = {};
					for ( var j = 0, colLen = cols.length; j < colLen; j++) {
						var col = cols[j];
						if (col.charAt(0) == "\""
								&& col.charAt(col.length - 1) == "\"") {
							col = col.substr(1, col.length - 2);
						}
						col = col.replace(/\"\"/g, "\"");
						if(j < fieldCols.length) {
							var fieldName = fieldCols[j];
							rowObj[fieldName] = col;
						}
						/*var fieldCol = fieldCols.eq(j);
						if (fieldCol && fieldCol.length) {
							var fieldName = fieldCol.attr("field");
							rowObj[fieldName] = col;
						}*/
					}
					rowData.push(rowObj);
				}
				if (opts.tree) {
					jwpf.setTreeTableData($(target).attr('id'), rowData, true,
							false);
				} else {
					jwpf.setTableData($(target).attr('id'), rowData, true,
							false);
				}
			}
		}

		/* 将剪贴板的内容复制到指定列 */
		function pasteColumnFromClipboard(text, fieldName) {
			var arr = text.split("\r\n");
			var len = arr.length;
			if (len) {
				var rowData = [];
				for ( var i = 0; i < len - 1; i++) {
					var rowObj = {};
					rowObj[fieldName] = arr[i].split(/\t+/)[0];
					rowData.push(rowObj);
				}
				if (opts.tree) {
					jwpf.setTreeTableData($(target).attr('id'), rowData, true,
							false);
				} else {
					jwpf.setTableData($(target).attr('id'), rowData, true,
							false, true);
				}
			}
		}

		keyCtr();
		pasteFromExcel();
		
		initHeader(target, opts);
	}
	
	//初始化表头，表头随滚动条浮动
	var initHeader = function (target, opts) {
        if (!opts.stickyHeader) {
            return;
        }
        
        var jqTable = $(target),
        	table = jqTable.datagrid("getPanel"),
        	table_body = table,
            table_id = jqTable.attr('id'),
            anchor_begin_id = table_id +'_sticky_anchor_begin',
            anchor_end_id = table_id +'_sticky_anchor_end',
            scrollContainer = jqTable.closest("div[region='center']");

        //console.log("init header:" + table_id);
        
        if($("#"+anchor_begin_id).length == 0) {
        	table_body.before(['<div id="', anchor_begin_id, '"></div>'].join(""));
        }
        if($("#"+anchor_end_id).length == 0) {
        	table_body.after(['<div id="', anchor_end_id, '"></div>'].join(""));
        }
        
        // render sticky on window scroll or resize
        //$(window).on('resize.'+table_id, table, render_sticky_header);
        scrollContainer.on('scroll.'+table_id, table, render_sticky_header);

        /*console.log(table_id + ":" + new Date().getTime() + "--init;start:" + $("#"+anchor_begin_id).offset().top 
        			+ ";end:" + $("#"+anchor_end_id).offset().top
        			+ ";parent:");*/
        //console.log($("#"+anchor_begin_id)[0].offsetParent);
        
        function render_sticky_header(event) {
            var table = event.data;
            if(table.is(":visible")) {
            	// window scroll top
                var t = scrollContainer.scrollTop();
                // top anchor scroll position, minus header height
                var e_start = $("#"+anchor_begin_id).offset().top;
                // bottom anchor scroll position, minus header height, minus sticky height
                var e_end = $("#"+anchor_end_id).offset().top;
                var e_stop = $("#"+anchor_begin_id).scrollTop();
                //console.log("1--" + table_id + ":" + new Date().getTime() + ";t:" + t +  ";start:" + e_start + ";end:" + e_end + ";scrolltop:" + e_stop);
                // show sticky when top anchor touches header, and when bottom anchor not exceeded
                if (e_start <= 0 && e_end > 0) {
                    match_position_x(event, t);
                } else {
                	table.data("startPos", t);
                    table.find("div.datagrid-header").css("position","static");
                }
            }
        }
        function match_position_x(event, t){
            var table = event.data;
            var header = table.find("div.datagrid-header");
            var startPos = table.data("startPos");
            header.css({
            	"position":"absolute",
            	"top":t-startPos
            });
            
            //var footer = table.find("div.datagrid-footer");
            /*console.log("1-footer:" + footer.offset().bottom);
            footer.css({
            	"position":"absolute",
            	"bottom":0
            });
			console.log("2-footer:" + footer.offset().bottom);*/
            //console.log("2--" + table_id + ":" + new Date().getTime() + "t:" + t + ",startPos:" + startPos + ";h:" + header.offset().top);
        }
    };
	
	
	// 判断是否空行
	function isEmptyRow(row) {
	   var flag=true;
	   $.each(row,function(k,v){
		   if(k!="isNewRecord" && k!="autoParentCode" && k!="autoCode" &&k!="_parentId"&& k!="state"){
			   // 为空v=false
			   // 不为空v=true
			   flag=flag&&!v;
		   }
	   });
	   return flag;
	};
	
	// 判断是否默认行
	function isDefaultRow(row, defaultRow) {
		var obj = $.extend(true, {}, row);
		for(var o in defaultRow) {
			if(defaultRow[o] === obj[o]) {
				obj[o] = undefined;
				if(obj[o+"_caption"]) {
					obj[o+"_caption"] = undefined;
				}
			} else {
				return false;
			}
		}
		var result = $.extend(true, {}, obj);
		return isEmptyRow(result);
	};
	
	/*拆分单元格*/
	function splitCells(target) {
		var panel = $(target).edatagrid("getPanel").panel("panel");
		panel.find("div.datagrid-body td").removeAttr("rowspan").show();
	}
	
	/*合并相同值的单元格*/
	function mergeEqualsCells(target) {
		var rows = $(target).edatagrid("getRows");
		var frozenColumnFields = $(target).edatagrid("getColumnFields", true);
		var columnFields = $(target).edatagrid("getColumnFields");
		
		/*拆分单元格*/
		$(target).edatagrid("splitCells");
		
		/*行排序 start*/
		if(rows.length>1) {
			for(var i=0; i<rows.length-1; i++) {
				for(var j=0; j<rows.length-i-1; j++) {
					var swap = _sorter(frozenColumnFields, j);
					if(swap === 0) {
						swap = _sorter(columnFields, j);
					} 
					if(swap > 0) {
						var rowData = rows[j];
						rows[j] = rows[j+1];
						rows[j+1] = rowData;
					}
				}
				/*防止排序过程触发onloadsuccess事件，refreshRow是刷新该行号减一*/
				$(target).edatagrid("refreshRow", rows.length-i-1);
			}
			$(target).edatagrid("refreshRow", 0);
		}
		/*行排序 end*/
		
		/*行合并 start*/
		if(rows.length > 1) {
			var notes = {};
			_creatNotes(frozenColumnFields, notes);
			_creatNotes(columnFields, notes);
			for(var i=1; i<rows.length; i++) {
				var mark = false;
				for(var k in notes) {
					if(mark) {
						if(i-notes[k].index > 1) {
							$(target).edatagrid("mergeCells", {index:notes[k].index, field:k, rowspan:i-notes[k].index});
						}
						notes[k].value = rows[i][k];
						notes[k].index = i;
						continue;
					}
					if(notes[k].value !== rows[i][k]) {
						if(i-notes[k].index > 1) {
							$(target).edatagrid("mergeCells", {index:notes[k].index, field:k, rowspan:i-notes[k].index});
						}
						notes[k].value = rows[i][k];
						notes[k].index = i;
						mark = true;
					}
				}
			}
			for(var k in notes) {
				if(rows.length-notes[k].index > 1) {
					$(target).edatagrid("mergeCells", {index:notes[k].index, field:k, rowspan:rows.length-notes[k].index});
				}
			}
		}
		/*行合并 end*/
		
		/*加_前缀的一般为，easyui控件方法的内部方法，增加代码的复用*/
		function _creatNotes(fields, notes) {
			$.each(fields, function(i, v) {
				var opts = $(target).edatagrid("getColumnOption", v);
				/*列属性mergeable，表示该列是否对value相同进行合并*/
				if(opts.mergeable) {
					notes[v] = {};
					notes[v].value = rows[0][v];
					notes[v].index = 0;
				}
			});
		}
		
		function _sorter(fields, index) {
			var swap = 0;
			$.each(fields, function(l, v) {
				var opts = $(target).edatagrid("getColumnOption", v);
				/*若列属性中，存在自定义排序器，则按照排序器方法排序，否则从小到大排序*/
				var sorter = opts.sorter ? opts.sorter : function(a, b) {
					if((a && b && a>b) || (!a && b)){
						return 1;
					}else if((a && b && a<b) || (!b && a)) {
						return -1;
					}else{
						return 0;
					}
				};
				/*列属性mergeable，表示该列是否对value相同进行合并*/
				if(opts.mergeable) {
					swap = sorter(rows[index][v],v);
					if(swap > 0){
						swap = 1;
						return false;
					} else if(swap < 0) {
						swap = -1;
						return false;
					}
				}
			});
			return swap;
		}
	}
	
	/*开始编辑单元格*/
	function beginCellEdit(target, cell) {
		var index = parseInt(cell.index);
		var field = cell.field;
		/*使单元格编辑中的事件，对treegrid有效，不过估计treegrid同样维护了一个datagrid的options，
		 * 不过为了防止以后treegrid独立开，所以在只需获取options时，对treegrid调用treegrid的options方法更合适*/
		//var opts = $(target).edatagrid("options");
		//因为发现edatagrid,datagrid的options都独立存储了关键信息，在多处被调用，不放便修改统一，只能以后编程时注意两者区分
		var opts = $.data(target, "datagrid").options;
		var tr = opts.finder.getTr(target, index);
		var td = tr.find("td[field=" + field + "]");
		var row = opts.finder.getRow(target, index);
		/*如果遇到合并单元格，则查找第一个td，即可见td*/
		if (!td.is(":visible")) {
			cell.index--;
			if(cell.index <= 0) {
				return;
			} else {
				return beginCellEdit(target, cell);
			}
		}
		/*确认正在编辑的行，正在编辑的行信息在edatagrid*/
		$.data(target, "edatagrid").options.editIndex = cell.index;
		if (td.hasClass("datagrid-cell-editing")) {
			return;
		}
		if (opts.onBeforeFieldEdit.apply(target, _588(target, [field, index, row])) === false) {
			return;
		}
		td.addClass("datagrid-cell-editing");
		_editCell(target, index, field);
		_resize(target);
		tr.find("div.datagrid-editable").each(function() {
			//需要处理onchange事件，初始化时不需要触发onchange事件
			var ed = $.data(this, "datagrid.editor");
			var _4e1 = $(ed.target);
			var combo = _4e1.data("combo");
			var comboOnChangeEvent = null;
			if(combo) {
				comboOnChangeEvent = combo.options.onChange;
				combo.options.onChange = function() {};
			}
			//取消textbox-onChange事件
			var textbox = _4e1.data("textbox");
			var textboxOnChangeEvent = null;
			if(textbox) {
				textboxOnChangeEvent = textbox.options.onChange;
				textbox.options.onChange = function() {};
			}
			
			ed.actions.setValue(ed.target, row[field]);
			
			if(textbox) {
				textbox.options.onChange = textboxOnChangeEvent;
			}
			if(combo) {
				combo.options.onChange = comboOnChangeEvent;
			}
		});
		_validate(target, index);
		opts.onBeginCellEdit.apply(target, _588(target, [field, index, row]));
		
		/*校验值*/
		function _validate(target, index) {
			var tr = $.data(target, "datagrid").options.finder.getTr(target, index);
			if (!tr.hasClass("datagrid-row-editing")
					&& !tr.hasClass("datagrid-cell-editing")) {
				return true;
			}
			var vbox = tr.find(".validatebox-text");
			vbox.validatebox("validate");
			vbox.trigger("mouseleave");
			var _6b9 = tr.find(".validatebox-invalid");
			return _6b9.length == 0;
		};
		
		/*回调编辑器的resize*/
		function _resize(target) {
			var dc = $.data(target, "datagrid").dc;
			dc.view.find("div.datagrid-editable").each(function() {
				var cell = $(this);
				var field = cell.parent().attr("field");
				var col = $(target).datagrid("getColumnOption", field);
				cell._outerWidth(col.boxWidth + col.deltaWidth - 1);
				var ed = $.data(this, "datagrid.editor");
				if (ed.actions.resize) {
					ed.actions.resize(ed.target, cell.width());
				}
			});
		};
		
		/*获取列属性*/
		function _getColumnOption(target, field) {
			function find(_640) {
				if (_640) {
					for ( var i = 0; i < _640.length; i++) {
						var cc = _640[i];
						for ( var j = 0; j < cc.length; j++) {
							var c = cc[j];
							if (c.field == field) {
								return c;
							}
						}
					}
				}
				return null;
			};
			var opts = $.data(target, "datagrid").options;
			var col = find(opts.columns);
			if (!col) {
				col = find(opts.frozenColumns);
			}
			return col;
		};
		
		/*尺寸自适应调整*/
		function _5af(target, index, _5b2) {
			var rows = $.data(target, "datagrid").data.rows;
			var opts = $.data(target, "datagrid").options;
			var dc = $.data(target, "datagrid").dc;
			if (!dc.body1.is(":empty")
					&& (!opts.nowrap || opts.autoRowHeight || _5b2)) {
				if (index != undefined) {
					var tr1 = opts.finder.getTr(target, index, "body", 1);
					var tr2 = opts.finder.getTr(target, index, "body", 2);
					_5b3(tr1, tr2);
				} else {
					var tr1 = opts.finder.getTr(target, 0, "allbody", 1);
					var tr2 = opts.finder.getTr(target, 0, "allbody", 2);
					_5b3(tr1, tr2);
					if (opts.showFooter) {
						var tr1 = opts.finder.getTr(target, 0, "allfooter", 1);
						var tr2 = opts.finder.getTr(target, 0, "allfooter", 2);
						_5b3(tr1, tr2);
					}
				}
			}
			_59e(target);
			if (opts.height == "auto") {
				var _5b4 = dc.body1.parent();
				var _5b5 = dc.body2;
				var _5b6 = _5b7(_5b5);
				var _5b8 = _5b6.height;
				if (_5b6.width > _5b5.width()) {
					_5b8 += 18;
				}
				_5b8 -= parseInt(_5b5.css("marginTop")) || 0;
				_5b4.height(_5b8);
				_5b5.height(_5b8);
				dc.view.height(dc.view2.height());
			}
			dc.body2.triggerHandler("scroll");
			function _5b3(trs1, trs2) {
				for ( var i = 0; i < trs2.length; i++) {
					var tr1 = $(trs1[i]);
					var tr2 = $(trs2[i]);
					tr1.css("height", "");
					tr2.css("height", "");
					var _5b9 = Math.max(tr1.height(), tr2.height());
					tr1.css("height", _5b9);
					tr2.css("height", _5b9);
				}
			};
			function _5b7(cc) {
				var _5ba = 0;
				var _5bb = 0;
				$(cc).children().each(function() {
					var c = $(this);
					if (c.is(":visible")) {
						_5bb += c._outerHeight();
						if (_5ba < c._outerWidth()) {
							_5ba = c._outerWidth();
						}
					}
				});
				return {
					width : _5ba,
					height : _5bb
				};
			};
			function _59e(target) {
				var _5a0 = $.data(target, "datagrid");
				var opts = _5a0.options;
				var dc = _5a0.dc;
				var wrap = _5a0.panel;
				var _5a1 = wrap.width();
				var _5a2 = wrap.height();
				var view = dc.view;
				var _5a3 = dc.view1;
				var _5a4 = dc.view2;
				var _5a5 = _5a3.children("div.datagrid-header");
				var _5a6 = _5a4.children("div.datagrid-header");
				var _5a7 = _5a5.find("table");
				var _5a8 = _5a6.find("table");
				view.width(_5a1);
				var _5a9 = _5a5.children("div.datagrid-header-inner").show();
				_5a3.width(_5a9.find("table").width());
				if (!opts.showHeader) {
					_5a9.hide();
				}
				_5a4.width(_5a1 - _5a3._outerWidth());
				_5a3.children()._outerWidth(_5a3.width());
				_5a4.children()._outerWidth(_5a4.width());
				var all = _5a5.add(_5a6).add(_5a7).add(_5a8);
				all.css("height", "");
				var hh = Math.max(_5a7.height(), _5a8.height());
				all._outerHeight(hh);
				dc.body1.add(dc.body2).children("table.datagrid-btable-frozen")
				.css({
					position : "absolute",
					top : dc.header2._outerHeight()
				});
				var _5aa = dc.body2.children("table.datagrid-btable-frozen")._outerHeight();
				var _5ab = _5aa + _5a6._outerHeight()
						+ _5a4.children(".datagrid-footer")._outerHeight();
				wrap.children(":not(.datagrid-view)").each(function() {
					_5ab += $(this)._outerHeight();
				});
				var _5ac = wrap.outerHeight() - wrap.height();
				var _5ad = wrap._size("minHeight") || "";
				var _5ae = wrap._size("maxHeight") || "";
				_5a3.add(_5a4).children("div.datagrid-body")
				.css({
					marginTop : _5aa,
					height : (isNaN(parseInt(opts.height)) ? "" : (_5a2 - _5ab)),
					minHeight : (_5ad ? _5ad - _5ac - _5ab : ""),
					maxHeight : (_5ae ? _5ae - _5ac - _5ab : "")
				});
				view.height(_5a4.height());
			};
		};
		
		/*创建单元格编辑元素*/
		function _editCell(target, index, field) {
			var opts = $.data(target, "datagrid").options;
			var tr = opts.finder.getTr(target, index);
			tr.find("td[field=" + field + "]").each(function() {
				var cell = $(this).find("div.datagrid-cell");
				var field = $(this).attr("field");
				var col = _getColumnOption(target, field);
				if (col && col.editor) {
					var type, options;
					if (typeof col.editor == "string") {
						type = col.editor;
					} else {
						type = col.editor.type;
						options = col.editor.options;
					}
					var editor = opts.editors[type];
					if (editor) {
						var oldHtml = cell.html();
						cell.addClass("datagrid-editable");
						cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td></td></tr></table>");
						cell.children("table").bind("click dblclick contextmenu", function(e) {
							e.stopPropagation();
						});
						//增加行数据缓存
						var row = opts.finder.getRow(target, index);
						options = $.extend(true, {}, options, {"rowData":row, "rowIndex":index});
						
						$.data(cell[0], "datagrid.editor", {
							actions : editor,
							target : editor.init(cell.find("td"), options),
							field : field,
							type : type,
							oldHtml : oldHtml
						});
					}
				}
			});
			_5af(target, index, true);
		};
		
	};
	
	/*结束编辑单元格，与取消编辑共用此方法*/
	function endCellEdit(target, cell, isCancelCellEdit) {
		var index = parseInt(cell.index);
		var field = cell.field;
		var _69c = $.data(target, "datagrid");
		var opts = _69c.options;
		var _69d = _69c.updatedRows;
		var _69e = _69c.insertedRows;
		var tr = opts.finder.getTr(target, index);
		var td = tr.find("td[field=" + field + "]");
		var row = opts.finder.getRow(target, index);
		if (!td.hasClass("datagrid-cell-editing")) {
			return;
		}
		if (!isCancelCellEdit) {
			if (!_a82(target, index, field)) {
				return;
			}
			var _69f = false;
			var changes = {};
			tr.find("div.datagrid-editable").each(function() {
				var _6a1 = $(this).parent().attr("field");
				var ed = $.data(this, "datagrid.editor");
				var t = $(ed.target);
				var _6a2 = t.data("textbox") ? t.textbox("textbox") : t;
				_6a2.triggerHandler("blur");
				var _6a3 = ed.actions.getValue(ed.target);
				if (row[_6a1] != _6a3) {
					row[_6a1] = _6a3;
					//combo类控件设置caption值
					if(ed.type && ed.type.indexOf("combo") >= 0) {
						var text = t.combo("getText");
						row[_6a1+"_caption"] = text;
					}
					_69f = true;
					changes[_6a1] = _6a3;
				}
			});
			if (_69f) {
				if ($.inArray(row, _69e) == -1) {
					if ($.inArray(row, _69d) == -1) {
						_69d.push(row);
					}
				}
				/*修改合并行的数据，合并之后显示的是第一行数据，不过在rows中每条相关数据都要同步修改*/
				var rowspan = td.attr("rowspan");
				if (rowspan) {
					for ( var i = 1; i < rowspan; i++) {
						var _row = opts.finder.getRow(target, index + i);
						_row[field] = row[field];
						if ($.inArray(_row, _69e) == -1) {
							if ($.inArray(_row, _69d) == -1) {
								_69d.push(_row);
							}
						}
					}
				}
			}
			opts.onEndCellEdit.apply(target, _588(target, [field, index, row, changes]));
		}
		td.removeClass("datagrid-cell-editing");
		_a84(target, index, field);
		$(target).datagrid("refreshRow", index);
		if (!isCancelCellEdit) {
			opts.onAfterFieldEdit.apply(target, _588(target, [field, index, row, changes]));
		} else {
			opts.onCancelCellEdit.apply(target, _588(target, [field, index, row]));
		}
	};
	
	/*验证输入是否合法*/
	function _a82(target, index, field) {
		var tr = $.data(target, "datagrid").options.finder.getTr(target, index);
		var td = tr.find("td[field=" + field + "]");
		if (!td.hasClass("datagrid-cell-editing")) {
			return true;
		}
		var vbox = td.find(".validatebox-text");
		vbox.validatebox("validate");
		vbox.trigger("mouseleave");
		var _6b9 = tr.find(".validatebox-invalid");
		return _6b9.length == 0;
	};
	
	function _a84(_6b5, _6b6, _a85) {
		var opts = $.data(_6b5, "datagrid").options;
		var tr = opts.finder.getTr(_6b5, _6b6);
		tr.children("td[field=" + _a85 + "]").each(function() {
			var cell = $(this).find("div.datagrid-editable");
			if (cell.length) {
				var ed = $.data(cell[0], "datagrid.editor");
				if (ed.actions.destroy) {
					ed.actions.destroy(ed.target);
				}
				cell.html(ed.oldHtml);
				$.removeData(cell[0], "datagrid.editor");
				cell.removeClass("datagrid-editable");
				cell.css("width", "");
			}
		});
	};
	
	/*treegrid的onBeforeFieldEdit与onBeginCellEdit没有index参数*/
	function _588(target, aa) {
		return aa; //$.data(target, "treegrid") ? aa.slice(1) : aa;
	};
	
	/*自定义edatagrid*/
	$.fn.edatagrid = function(options, param) {
		if (typeof options == 'string') {
			var method = $.fn.edatagrid.methods[options];
			if (method){
				return method(this, param);
			} else {
				var opt = $.data(this[0], "edatagrid");
				if(opt && opt.options && opt.options.tree) {
					return this.treegrid(options, param);
				} else {
					return this.datagrid(options, param);
				}
			}
		}
		
		options = options || {};
		return this.each(function(){
			var state = $.data(this, 'edatagrid');
			if (state){
				$.extend(state.options, options);
			} else {
				if(options.tree){
					state = $.data(this,"edatagrid",{
						options:$.extend({editing: true},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),options)
						});
					if(state.lines){
						$(this).addClass("tree-lines");
					}
				}else{
					$.data(this, 'edatagrid', {
						options: $.extend({}, $.fn.edatagrid.defaults, $.fn.edatagrid.parseOptions(this), options)
					});
				}
			}
			buildGrid(this);
		});
	};
	
	$.fn.edatagrid.parseOptions = function(target){
		return $.extend({}, $.fn.datagrid.parseOptions(target));
	};
	
	/**edatagrid新增的方法*/
	$.fn.edatagrid.methods = {
		options : function(jq) {
			//目前对于edatagrid获取opts必须从datagrid或treegrid，如从edatagrid获取将导致buildgrid方法中附加在options中的事件无法获取。
			//edatagrid仅保存有设计器中定义的options的事件与默认值。
			var opts = $.data(jq[0], 'edatagrid').options;
			return opts;
		},
		enableEditing : function(jq) {
			return jq.each(function() {
				var opts = $.data(this, 'edatagrid').options;
				opts.editing = true;
				opts.checkOnSelect = !opts.editing;
				$(this).datagrid('getPanel').panel('panel').find(
						"div.datagrid-toolbar a").linkbutton("enable");
			});
		},
		validateCol : function(jq, obj) {// 检验当前列
			if ($.data(obj, "validatebox")) {
				return $(obj).validatebox('isValid');
			} else {
				return true;
			}
		},
		validateRows : function(jq, rowObj) {// 检验行
			var rowFields = jq.datagrid('getColumnFields');
			var flag = true;
			for ( var i = 0; i < rowFields.length; i++) {
				var field = rowFields[i];
				var opt = jq.datagrid('getColumnOption', field);
				if (opt.required) {
					if (rowObj[field] !== undefined && rowObj[field] !== null
							&& rowObj[field] !== "") {
						flag = true;
					} else {
						$.messager.alert('提示信息', '[' + opt.title + ']为必输项，请填写',
								'info');
						return false;
					}
				}
			}
			return flag;
		},
		disableEditing : function(jq) {
			return jq.each(function() {
				var opts = $.data(this, 'edatagrid').options;
				opts.editing = false;
				opts.checkOnSelect = !opts.editing;
				$(this).datagrid('getPanel').panel('panel').find(
						"div.datagrid-toolbar a:not(.enableInView):not(:has(span.enableInView))")
						.linkbutton("disable");
			});
		},// 开启单行可编辑
		enableEditRow : function(jq, indexOpt) {
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				if (!opts.editRowMap) {
					opts.editRowMap = {};
				}
				opts.editRowMap[indexOpt.index.toString()] = true;// 表示index所在行可编辑
				if (indexOpt.isAutoFocus !== false) { // 自动聚焦
					dg.edatagrid("editCol", indexOpt);// 字段可编辑
					dg.focusEditor(indexOpt.field);// 字段聚焦
				}
			});
		},// 关闭单行可编辑
		disableEditRow : function(jq, index) {
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				if (opts.editRowMap) {
					delete opts.editRowMap[index.toString()];
				}
			});
		},// 检查是否可编辑行
		checkEditRow : function(jq, index) {
			var opts = $.data(jq[0], 'edatagrid').options;
			if (opts.editRowMap && opts.editRowMap[index.toString()]) {
				return true;
			} else {
				return false;
			}
		},// 开启单行可编辑，根据属性查记录
		enableEditRowByAttr : function(jq, indexOpt) {
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var allRows = [];
				if (opts.tree) {
					allRows = dg.edatagrid('getAllNodes');
				} else {
					allRows = dg.edatagrid('getRows');
				}
				var selRows = [];
				for ( var i = 0, len = allRows.length; i < len; i++) {
					var row = allRows[i];
					if (indexOpt.attrKey) {
						if (row[indexOpt.attrKey] == indexOpt.attrVal) {
							if (opts.tree) {
								selRows.push(row.autoCode);
							} else {
								selRows.push(i);
							}
						}
					} else { // attrKey为空时，默认开启全部可编辑
						if (opts.tree) {
							selRows.push(row.autoCode);
						} else {
							selRows.push(i);
						}
					}
				}
				for ( var i = 0, len = selRows.length; i < len; i++) {
					indexOpt["index"] = selRows[i];
					if (i == 0) {
						indexOpt["isAutoFocus"] = (indexOpt["isAutoFocus"] && true);
					} else {
						indexOpt["isAutoFocus"] = false;
					}
					dg.edatagrid("enableEditRow", indexOpt);
				}
			});
		},
		editRow : function(jq, index) {// 编辑行
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var editIndex = opts.editIndex;
				if (editIndex != index) {
					if (dg.datagrid('validateRow', editIndex)) {
						dg.datagrid('endEdit', editIndex);
						dg.datagrid('beginEdit', index);
						opts.editIndex = index;
					} else {
						setTimeout(function() {
							dg.datagrid('selectRow', editIndex);
						}, 0);
					}
				}
			});
		},
		editCol : function(jq, opt) {// 编辑单元格
			var index = parseInt(opt.index);
			var field = opt.field;
			return jq.each(function() {
				var dg = $(this);
				// 这个有好多地方引用了，最新的正在编辑位置需从edatagrid中取，不能在datagrid取
				var opts = $.data(this, 'edatagrid').options; 
				var editIndex = opts.editIndex;
				if (editIndex != index || editCol != field) {
					var tr = opts.finder.getTr(this, editIndex);
					var td = tr.find("td[field=" + opts.editCol + "]");
					var div = td.find("div.datagrid-editable");
					var input = div.find("input.validatebox-text");
					if (input && input.length > 0) {
						if (dg.edatagrid('validateCol', input[0])) {
							var editCol = opts.editCol;
							var editOpt = {
								"index" : editIndex,
								"field" : editCol
							};
							dg.edatagrid('endCellEdit', editOpt);
							dg.edatagrid('beginCellEdit', opt);
							opts.editIndex = opt.index;//对合并单元格的编辑操作，可能会引起当前编辑行的重定位
							opts.editCol = field;
						} else {
							setTimeout(function() {
								dg.datagrid('selectRow', editIndex);
							}, 0);
						}
					} else {
						var editCol = opts.editCol;
						var editOpt = {
							"index" : editIndex,
							"field" : editCol
						};
						dg.edatagrid('endCellEdit', editOpt);
						dg.edatagrid('beginCellEdit', opt);
						opts.editIndex = opt.index;//对合并单元格的编辑操作，可能会引起当前编辑行的重定位
						opts.editCol = field;
					}
				}

			});
		},
		ChildTabs : function(jq) {
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var editIndex = opts.editIndex;
				var editCol = opts.editCol;
				if (editIndex && editCol) {
					dg.edatagrid('editCol', {
						"index" : editIndex,
						"field" : editCol
					});
					dg.focusEditor(editCol);
				} else {
					dg.edatagrid('addRow');
				}
			});
		},
		/*添加新行*/
		addRow : function(jq, row) {
			return jq.each(function() {
				var dg = $(this);
				//注意该写法不会获取到buildgrid中新增的属性，通过后续操作后datagrid，treegrid与edatagrid中的options和其他状态并不同步
				var opts = $.data(this, 'edatagrid').options;
				if (opts.editIndex >= 0) {
					if (!dg.datagrid('validateRow', opts.editIndex)) {
						dg.datagrid('selectRow', opts.editIndex);
						return;
					}
					var editOpt = {
						"index" : opts.editIndex,
						"field" : opts.editCol
					};
					if (opts.editIndex !== null && opts.editCol !== null) {
						dg.edatagrid('endCellEdit', editOpt);
					}
				}
				var defaultRow = $.extend({}, opts.defaultRow);
				var aRow = {};
				if (opts.tree) {
					var newcode = "";
					if (row && row.autoParentCode) {
						var pCode = row.autoParentCode;
						var childList = dg.treegrid('getChildren', pCode);
						newcode = dg.createNewCode(pCode, childList);
					} else {
						var rootList = dg.treegrid('getRoots');
						newcode = dg.createNewCode("", rootList);
					}
					aRow = {
						"_parentId" : null,
						"autoCode" : newcode,
						"autoParentCode" : null,
						"isNewRecord" : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if (row) {
						aRow = $.extend({}, aRow, row);
					}
					aRow["_parentId"] = aRow["autoParentCode"];
					dg.treegrid('append', {
						parent : aRow["_parentId"],
						data : [ aRow ]
					});
					/*如果列属性存在需要合并的列，则在每次新增时，进行合并相同值的单元格
					为提高性能，列属性是否存在需要合并列在模版文件中判断*/
					if (opts.mergeable) {
						dg.edatagrid("mergeEqualsCells");
					}
					var field = opts.treeField;
					newcode = aRow["autoCode"];
					opts.editCol = field;
					opts.editIndex = newcode;
					var opt = {
						"index" : newcode,
						"field" : field
					};
					if (aRow["_isAutoFocus_"] !== false) {
						dg.edatagrid('beginCellEdit', opt);
						opts.editIndex = opt.index;
					}
					if (row != false && aRow["_isAutoFocus_"] !== false) {
						dg.focusEditor(field);
					}
				} else {
					aRow = {
						isNewRecord : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if (row) {
						aRow = $.extend({}, aRow, row);
					}
					dg.datagrid('appendRow', aRow);
					/*如果列属性存在需要合并的列，则在每次新增时，进行合并相同值的单元格
					为提高性能，列属性是否存在需要合并列在模版文件中判断*/
					if (opts.mergeable) {
						dg.edatagrid("mergeEqualsCells");
					}
					var rows = dg.datagrid('getRows');
					opts.editIndex = rows.length - 1;
					var tr = opts.finder.getTr(this, opts.editIndex);
					var tdList = tr.find("td[field]");
					for ( var i = 0; i < tdList.length; i++) {
						var div = $(tdList[i]).find("div.datagrid-cell-check");
						if (div.length == 0) {
							opts.editCol = $(tdList[i]).attr("field");
							break;
						}
					}
					var field = opts.editCol;
					var opt = {
						"index" : opts.editIndex,
						"field" : field
					};
					if (aRow["_isAutoFocus_"] !== false) {
						dg.edatagrid('beginCellEdit', opt);
						opts.editIndex = opt.index;
					}
					if (row != false && aRow["_isAutoFocus_"] !== false) {
						dg.focusEditor(field);
					}
				}
				if (opts.onAdd) opts.onAdd.call(this, opts.editIndex, aRow);
			});
		},
		insertNewRow : function(jq, index) {// 插入新行
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var defaultRow = $.extend({}, opts.defaultRow);
				if (opts.tree) {
					var pCode = index.autoCode;
					var pLength = pCode.length;
					var newcode = "";
					var childList = dg.treegrid('getChildren', pCode);
					var newcode = dg.createNewCode(pCode, childList);
					var aRow = {
						"_parentId" : pCode,
						"autoCode" : newcode,
						"autoParentCode" : pCode,
						"isNewRecord" : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if (index.row) {
						aRow = $.extend({}, aRow, index.row);
					}
					aRow["_parentId"] = aRow["autoParentCode"];
					var newChildData = [ aRow ];
					dg.treegrid('append', {
						parent : pCode,
						data : newChildData
					});
					var field = opts.treeField;
					newcode = aRow["autoCode"];
					dg.edatagrid('editCol', {
						"index" : newcode,
						"field" : field
					});
					dg.focusEditor(field);
					if (opts.onAdd)
						opts.onAdd.call(this, newcode, aRow);
				} else {
					if (opts.editIndex >= 0) {
						if (!dg.datagrid('validateRow', opts.editIndex)) {
							dg.datagrid('selectRow', opts.editIndex);
							return;
						}
						var editOpt = {
							"index" : opts.editIndex,
							"field" : opts.editCol
						};
						dg.edatagrid('endCellEdit', editOpt);
					}
					var rows = dg.datagrid('getRows');
					var aRow = {
						isNewRecord : true
					};
					aRow = $.extend({}, defaultRow, aRow);
					if (index >= 0 && index <= rows.length) {
						dg.datagrid('insertRow', {
							index : index,
							row : aRow
						});
						// rows = dg.datagrid('getRows');
						opts.editIndex = index;
					} else {
						dg.datagrid('appendRow', aRow);
						// rows = dg.datagrid('getRows');
						// opts.editIndex = rows.length - 1;
						opts.editIndex = rows.length;
					}
					var tr = opts.finder.getTr(this, opts.editIndex);
					var tdList = tr.find("td[field]");
					for ( var i = 0; i < tdList.length; i++) {
						var div = $(tdList[i]).find("div.datagrid-cell-check");
						if (div.length == 0) {
							opts.editCol = $(tdList[i]).attr("field");
							break;
						}
					}
					if(!dg.edatagrid("options").mergeable){
						var field = opts.editCol;
						var opt = {
							"index" : opts.editIndex,
							"field" : field
						};
						dg.edatagrid('beginCellEdit', opt);
						opts.editIndex = opt.index;
						dg.focusEditor(field);
					}
					if (opts.onAdd)
						opts.onAdd.call(this, opts.editIndex, aRow);
				}
			});
		},
		saveRow : function(jq) {// 保存edatagrid中的数据
			var opts = jq.edatagrid('options');
			var index = parseInt(opts.editIndex);
			var field = opts.editCol;
			if ((index || index == 0) && field) {
				var editOpt = {
					"index" : index,
					"field" : field
				};
				jq.edatagrid('endCellEdit', editOpt);
			}
			var defaultRow = opts.defaultRow || {};
			var allRows = [];
			if (opts.tree) {
				allRows = jq.edatagrid('getAllNodes');
			} else {
				allRows = jq.edatagrid('getRows');
			}
			var rows = [];
			for ( var k = 0, len = allRows.length; k < len; k++) {
				if ($.isEmptyObject(defaultRow)) {// 默认值为空
					if (!isEmptyRow(allRows[k])) {// 判断空值行
						// 校验
						if (jq.edatagrid('validateRows', allRows[k])) {
							rows.push(allRows[k]);
						} else {
							return false;
						}
					}
				} else {
					if (!isDefaultRow(allRows[k], defaultRow)) {// 判断默认行
						// 校验
						if (jq.edatagrid('validateRows', allRows[k])) {
							rows.push(allRows[k]);
						} else {
							return false;
						}
					}
				}
			}
			return rows;
		},// 批量删除行
		deleteRows : function(jq, rows) {
			if (rows && rows.length) {
				var lastDeleteIndex = 0;
				for ( var i = rows.length - 1; i >= 0; i--) {
					var row = rows[i];
					var index = parseInt(jq.edatagrid('getRowIndex', row));
					jq.edatagrid("deleteRow", index);
					lastDeleteIndex = index;
				}
				if (lastDeleteIndex > 0) {
					var allRows = jq.edatagrid("getRows");
					for ( var i = lastDeleteIndex, len = allRows.length; i < len; i++) {
						jq.edatagrid("refreshRow", i);
					}
				}
				var opts = jq.edatagrid('options');
				opts.editIndex = null;
				opts.editCol = null;
			}
		},
		validEmptyOrDefaultRow : function(jq, row) {
			var opts = jq.edatagrid('options');
			var defaultRow = opts.defaultRow || {};
			if ($.isEmptyObject(defaultRow)) {
				return isEmptyRow(row);
			} else {
				return isDefaultRow(row, defaultRow);
			}
		},
		clearColumnFilter : function(jq) {
			return jq.each(function() {
				$(this).removeData("baseRows");
				$(this).removeData("distic");
				var dgId = $(this).attr("id");
				var menuClass = "div._dg_tmenu_" + dgId;
				$(menuClass).remove();
			});
		},
		getAllNodes : function(jq) {
			var root = jq.treegrid('getRoots');
			var dataArr = [];
			jq.getTreeData(root, dataArr);
			return dataArr;

		},
		removeNodes : function(jq, nodeData) {
			return jq.each(function() {
				var select = [];
				var delArr = $(this).data("deleteData");
				delArr = delArr || [];
				select.push(nodeData);
				var dataArr = [];
				$(this).getTreeData(select, dataArr);
				if (dataArr.length > 0) {
					for ( var i = 0; i < dataArr.length; i++) {
						var id = dataArr[i].id;
						if (id) {
							delArr.push(dataArr[i]);
						}
					}
				}
				$(this).data("deleteData", delArr);
				$(this).treegrid('remove', nodeData.autoCode);
			});
		},
		removeAllNodes : function(jq) {
			return jq.each(function() {
				var dg = $(this);
				var roots = dg.treegrid("getRoots");
				if (roots && roots.length) {
					for ( var i = 0, len = roots.length; i < len; i++) {
						dg.edatagrid("removeNodes", roots[i]);
					}
				}
			});
		},
		getDeleteNodes : function(jq) {
			return jq.data("deleteData");
		},
		update : function(jq, data) {// 更新edatagrid
			return jq.each(function() {
				var tg = $(this);
				var opts = tg.edatagrid('options');
				var currentCode = data.id;
				var _dc = {};
				var node = tg.treegrid('find', currentCode);
				var pCode = node.autoParentCode;
				var nodesArr = [];
				if (pCode) {
					var p = tg.treegrid('getParent', currentCode);
					nodesArr = p.children;
				} else {
					nodesArr = tg.treegrid('getRoots');
				}
				for ( var i = 0; i < nodesArr.length; i++) {
					if (nodesArr[i].autoCode == currentCode) {
						if (data.update) {// 更新
							_dc = $.extend(nodesArr[i], data.row);
						} else {// 替换
							_dc = data.row;
						}
						nodesArr[i] = _dc;
						break;
					}
				}
				var _dd = tg.treegrid("getLevel", data.id) - 1;
				var _de = opts.rowStyler ? opts.rowStyler.call(this, _dc) : "";
				function _df(_e0) {
					var _e1 = tg.treegrid("getColumnFields", _e0);
					var tr = opts.finder.getTr(this, data.id, "body", (_e0 ? 1
							: 2));
					var _e2 = tr.find("div.datagrid-cell-rownumber").html();
					var _e3 = tr.find(
							"div.datagrid-cell-check input[type=checkbox]").is(
							":checked");
					tr.html(opts.view.renderRow(this, _e1, _e0, _dd, _dc));
					tr.attr("style", _de || "");
					tr.find("div.datagrid-cell-rownumber").html(_e2);
					if (_e3) {
						tr.find("div.datagrid-cell-check input[type=checkbox]")
								._propAttr("checked", true);
					}
				}
				;
				_df.call(this, true);
				_df.call(this, false);
				tg.treegrid("fixRowHeight", data.id);
			});
		},
		cancelRow : function(jq) {
			return jq.each(function() {
				var index = parseInt($(this).edatagrid('options').editIndex);
				$(this).datagrid('cancelEdit', index);
			});
		},
		destroyRow : function(jq) {
			return jq.each(function() {
				var dg = $(this);
				var opts = $.data(this, 'edatagrid').options;
				var row = dg.datagrid('getSelected');
				if (!row) {
					$.messager.show({
						title : opts.destroyMsg.norecord.title,
						msg : opts.destroyMsg.norecord.msg
					});
					return;
				}
				$.messager.confirm(
					opts.destroyMsg.confirm.title,
					opts.destroyMsg.confirm.msg,
					function(r) {
						if (r) {
							var index = dg.datagrid('getRowIndex', row);
							if (row.isNewRecord) {
								dg.datagrid('cancelEdit',index);
								// add by GaoXJ 2012-06-03
								dg.datagrid('deleteRow',index);
							} else {
								if (opts.destroyUrl) {
									$.post(
										opts.destroyUrl,
										{
											id : row.id
										},
										function() {
											if (opts.tree) {
												dg.datagrid('reload');
												var t = $(opts.tree);
												var node = t.tree('find',row.id);
												if (node) {
													t.tree('remove',node.target);
												}
											} else {
												dg.datagrid('cancelEdit',index);
												dg.datagrid('deleteRow',index);
											}
											opts.onDestroy.call(dg[0],index,row);
										}
									);
								} else {
									dg.datagrid('cancelEdit',index);
									dg.datagrid('deleteRow',index);
								}
							}
						}
					}
				);
			});
		},
		/*合并相同值的单元格*/
		mergeEqualsCells : function(jq) {
			return jq.each(function(){
				mergeEqualsCells(this);
			});
		},
		/*拆分单元格*/
		splitCells : function(jq) {
			return jq.each(function(){
				splitCells(this);
			});
		},
		/*开始编辑单元格*/
		beginCellEdit : function(jq, cell) {
			return jq.each(function() {
				beginCellEdit(this, cell);
			});
		},
		/*结束编辑单元格*/
		endCellEdit : function(jq, cell) {
			return jq.each(function() {
				endCellEdit(this, cell, false);
			});
		},
		/*取消编辑单元格*/
		cancelCellEdit : function(jq, cell) {
			return jq.each(function() {
				endCellEdit(this, cell, true);
			});
		}
	};

	$.fn.edatagrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
		mergeable : false,//是否存在合并相同值的单元格，为了增加性能标识在模版文件根据列属性自动生成。
		editing : true,//可编辑，默认单击单元格进行编辑
		stickyHeader : true, //固定表头，表头可以浮动
		editIndex : -1,
		destroyMsg : {
			norecord : {
				title : 'Warning',
				msg : 'No record is selected.'
			},
			confirm : {
				title : 'Confirm',
				msg : 'Are you sure you want to delete?'
			}
		},
		destroyConfirmTitle : 'Confirm',
		destroyConfirmMsg : 'Are you sure you want to delete?',

		url : null, // return the datagrid data
		saveUrl : null, // return the added row
		updateUrl : null, // return the updated row
		destroyUrl : null, // return {success:true}

		tree : null, // the tree selector
		// treeUrl: null, // return tree data
		// treeDndUrl: null, // to process the drag and drop operation, return
		// {success:true}
		// treeTextField: 'name',
		// treeParentField: 'parentId',

		onAdd : function(index, row) {
		},
		onSave : function(index, row) {
		},
		onDestroy : function(index, row) {
		},
		
		/* begin add editCell event on 2015-07-01 */
		onBeforeFieldEdit : function(field, rowIndex, rowData) {
		},
		onBeginCellEdit : function(field, rowIndex, rowData) {
		},
		onEndCellEdit : function(field, rowIndex, rowData, changes) {
		},
		onAfterFieldEdit : function(field, rowIndex, rowData, changes) {
		},
		onCancelCellEdit : function(field, rowIndex, rowData) {
		}
		/* end add editCell event on 2015-07-01 */
	});
	
})(jQuery);

/*为jQuery对象添加的一些方法*/
(function($) {

	$.fn.setCursorPosition = function(position) {
		if (this.lengh == 0)
			return this;
		return $(this).setSelection(position, position);
	};

	$.fn.setSelection = function(selectionStart, selectionEnd) {
		if (this.lengh == 0)
			return this;
		input = this[0];
		if ($(input).is(":hidden")) {
			input = $(input).next().find("input:visible")[0];
		}
		if (input) {
			if (input.createTextRange) {
				var range = input.createTextRange();
				range.collapse(true);
				range.moveEnd('character', selectionEnd);
				range.moveStart('character', selectionStart);
				range.select();
			} else if (input.setSelectionRange) {
				input.focus();
				try {
					input.setSelectionRange(selectionStart, selectionEnd);
				} catch (e) {
				}
			}
		}
		return this;
	};

	$.fn.focusEnd = function() {
		if ($(this).is(":hidden")) {
			var value = $($(this).next().find("input:visible")[0]).val();
			if (value != null) {
				var length = value.length;
				this.setCursorPosition(length);
			}
		} else if (this.val() != null) {
			var length = this.val().length;
			this.setCursorPosition(length);
		}
	};

	$.fn.focusEditor = function(field) {// edatagrid聚焦方法
		var opts = $(this).edatagrid("options");
		var editor = $(this).edatagrid('getEditor', {
			index : opts.editIndex,
			field : field
		});
		if (editor) {
			var _4a = $(editor.target);
			if (_4a.hasClass("combo-f")) {
				var _4a_opt = _4a.combo("options");
				if(_4a_opt && !_4a_opt["readonly"] && !_4a_opt["disable"])
					_4a.combo('showPanel');
			}
			editor.target.focusEnd();
		} else {
			var editors = $(this).edatagrid('getEditors', opts.editIndex);
			if (editors.length) {
				editors[0].target.focus();
			}
		}
	};

	$.fn.getSelectionStart = function() {
		if (this.lengh == 0)
			return -1;
		input = this[0];
		var pos = input.value.length;
		if (input.createTextRange) {
			var r = document.selection.createRange().duplicate();
			r.moveEnd('character', input.value.length);
			if (r.text == '')
				pos = input.value.length;
			pos = input.value.lastIndexOf(r.text);
		} else if (typeof (input.selectionStart) != "undefined")
			pos = input.selectionStart;

		return pos;
	};

	$.fn.getSelectionEnd = function() {
		if (this.lengh == 0)
			return -1;
		input = this[0];
		var pos = input.value.length;
		if (input.createTextRange) {
			var r = document.selection.createRange().duplicate();
			r.moveStart('character', -input.value.length);
			if (r.text == '')
				pos = input.value.length;
			pos = input.value.lastIndexOf(r.text);
		} else if (typeof (input.selectionEnd) != "undefined")
			pos = input.selectionEnd;

		return pos;
	};

	$.fn.getCursorPosition = function() {
		if (this.lengh == 0)
			return -1;
		return $(this).getSelectionStart();
	};
	
	$.fn.createNewCode = function(pCode, childList) {
		var maxVal = "";
		if (childList && childList.length > 0) {
			var codeArr = [];
			for ( var i = 0; i < childList.length; i++) {
				var ccode = childList[i].autoCode;
				var lastcode = ccode.substring(pCode.length, ccode.length);
				codeArr.push(parseInt(lastcode, 10));
			}

			if (codeArr.length > 0) {
				var maxv = Math.max.apply(null, codeArr);
				maxv = maxv + 1;
				maxVal = maxv.toString();
				var len = 4 - maxVal.length;
				for ( var k = 0; k < len; k++) {
					maxVal = "0" + maxVal;
				}
			}
		} else {
			maxVal = "0000";
		}
		return pCode + maxVal;
	};
	
	$.fn.getTreeData = function(root, dataArr) {
		for ( var k = 0; k < root.length; k++) {
			if (root[k]) {
				dataArr.push(root[k]);
				var child = root[k].children;
				if (child && child.length > 0) {
					$(this).getTreeData(child, dataArr);
				}
			}
		}
	};
	
	$.fn.getSelection = function() {
		if (this.lengh == 0)
			return -1;
		var s = $(this).getSelectionStart();
		var e = $(this).getSelectionEnd();
		return this[0].value.substring(s, e);
	};

	$.fn.pasteEvents = function(delay) {
		if (delay == undefined)
			delay = 20;
		return $(this).each(function() {
			var $el = $(this);
			$el.on("paste", function() {
				$el.trigger("prepaste");
				setTimeout(function() {
					$el.trigger("postpaste");
				}, delay);
			});
		});
	};
})(jQuery);